package com.xzy.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


public class jdbcUtils {
    private static DataSource source;
    private static ThreadLocal<Connection> ThreadLocalConn = new ThreadLocal<>();//同一线程共享对象(能够在同一线程中保存对象,线程执行过程中不论何时获取都是同一对象)

    static {
        try {

            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties prop = new Properties();
            prop.load(in);
            source = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取数据库连接
     * 当ThreadLoca中有对象时,取出该对象返回
     * 当ThreadLoca没有对象时,将从连接池中取出的连接对象存入ThreadLoca,以便有可能的事务后续取出(事务应该使用同一连接并同时提交和关闭)
     * @return
     */
    public static Connection getConnection() {
        Connection connection = ThreadLocalConn.get();

        if(connection==null){
        try {
            connection = source.getConnection();
            ThreadLocalConn.set(connection); // 保存到ThreadLocal对象中，供后面的jdbc操作使用
            connection.setAutoCommit(false);//设置手动提交
            return connection;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        }else {
            return connection;
        }
        return null;
    }

    public static void clossAndCommit(){

        Connection conn = ThreadLocalConn.get();//获取线程中保存的conn对象
        if(conn!=null){
            try {
                conn.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        ThreadLocalConn.remove();//移除线程中conn对象

    }
    public static void clossandBack(){

        Connection conn = ThreadLocalConn.get();//获取线程中保存的conn对象
        if(conn!=null){
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        ThreadLocalConn.remove();//移除线程中conn对象

    }



}

